package com.zeroes.cons;



import org.zeroes.common_prelude.CGSize;

import android.util.DisplayMetrics;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.view.MotionEvent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class ConstructoidActivity<DisplayMetrics> extends Activity implements SensorEventListener{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        
		/*   LANDSCAPE  */
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		
		/*   PORTRAIT  */
		//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		
		mGLSurfaceView = new GLSurfaceView(this);
        ZSGameOptions gameoptions = new ZSGameOptions(ZSGameManager.GAME_TYPE_SVG_WITH_JAVASCRIPT);
	//	ZSGameOptions gameoptions = new ZSGameOptions(ZSGameManager.GAME_TYPE_ALL_PURE_JAVA);
        gameoptions.setJSSource("eve.js");
        gameoptions.setSVGResource(R.raw.test1);
        gameoptions.useAccelerometer=true;
        
        if (detectOpenGLES20()) 
        {
            // Tell the surface view we want to create an OpenGL ES 2.0-compatible
            // context, and set an OpenGL ES 2.0-compatible renderer.
            mGLSurfaceView.setEGLContextClientVersion(2);
            
            GLWrap = new ZSRenderer(this);
            mGLSurfaceView.setRenderer(GLWrap);
            // GAME OPTIONS

            
            ZSGameManager.AskMe().useRenderer(GLWrap).toRun(new MyGame(gameoptions));
          //  ZSGameManager.AskMe().toRun(new MyGame());
        } 
        else
        {
        	Log.e("MultiTexture", "OpenGL ES 2.0 not supported on device.  Exiting...");
        	finish();
           
        }
        if(gameoptions.useAccelerometer){
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		sensorManager.registerListener(this,
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
        }
        setContentView(mGLSurfaceView);
        
    }
    
    private boolean detectOpenGLES20() 
    {
        ActivityManager am =
            (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ConfigurationInfo info = am.getDeviceConfigurationInfo();
        return (info.reqGlEsVersion >= 0x20000);
    }

	@Override
	public void onSensorChanged(SensorEvent event) {
		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
			//getAccelerometer(event);
			ZSGameManager.AskMe().dispatchAccelerometerData(event);
		}

	}
	private void getAccelerometer(SensorEvent event) {
		float[] values = event.values;
		// Movement
		float x = values[0];
		float y = values[1];
		float z = values[2];
		//Log.v("gtrans", "Acc x:"+x+" "+y+" "+z);
		float accelationSquareRoot = (x * x + y * y + z * z)
				/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
		/*long actualTime = System.currentTimeMillis();
		if (accelationSquareRoot >= 2) //
		{
			if (actualTime - lastUpdate < 200) {
				return;
			}
			lastUpdate = actualTime;
			Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT)
					.show();
			if (color) {
				view.setBackgroundColor(Color.GREEN);

			} else {
				view.setBackgroundColor(Color.RED);
			}
			color = !color;
		}*/
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}
    @Override
    protected void onResume() 
    {
    	resumes++;
    	Log.v("gtrans", "ON RESUME"+ resumes);
        // Ideally a game should implement onResume() and onPause()
        // to take appropriate action when the activity looses focus
        super.onResume();
        mGLSurfaceView.onResume();
        SoundEngine.sharedEngine().resumeSound();
        if(ZSGameManager.AskMe().forCurrentGame().gameOptions.useAccelerometer){
        sensorManager.registerListener(this,
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
        }
        if(resumes>1)
        ZSGameManager.AskMe().resumeCurrentGame();
    }

    @Override
    protected void onPause() 
    {
    	Log.v("gtrans", "ON PAUSE");
        // Ideally a game should implement onResume() and onPause()
        // to take appropriate action when the activity looses focus
        super.onPause();
        mGLSurfaceView.onPause();
        SoundEngine.sharedEngine().pauseSound();
        if(ZSGameManager.AskMe().forCurrentGame().gameOptions.useAccelerometer){
        sensorManager.unregisterListener(this);
        }
        ZSGameManager.AskMe().pauseCurrentGame();
        //finish();
    }
    @Override
    protected void onStop(){
    	super.onStop();
    	//SoundEngine.sharedEngine().stopSound();
    	// finish();
    	Log.v("gtrans", "ON STOP");
    }
    
    @Override
	public boolean onTouchEvent(MotionEvent e) {
		
    	ZSGameManager.AskMe().dispatchTouch(e);
    	return true;
	}

    private GLSurfaceView mGLSurfaceView;
    private SensorManager sensorManager;
    private int resumes=0;
    public ZSRenderer GLWrap;
    
    public int getResumes(){
    	return this.resumes;
    }
    
    public CGSize getMetrics(){
    	
    	Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
    	int width = display.getWidth();
    	int height = display.getHeight();
    	return CGSize.make(width, height);
    }
    
    public void toLandscape(){
    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    	
    }
    
    public void toPortrait(){
    	
    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    
    
}